//go:build btree
// +build btree

package auction

import (
	btree "github.com/kjx98/go-btree"
)

type Tree struct {
	tree *btree.Map[oidPriceType, *simOrderType]
}

type Iterator struct {
	it *btree.MapIter[oidPriceType, *simOrderType]
}

//type TreeNode = rbtree.Node

func NewTree(cmpF btree.LessFunc[oidPriceType]) *Tree {
	var tree = Tree{}
	tree.tree = btree.MapNew[oidPriceType, *simOrderType](cmpF)
	if tree.tree != nil {
		return &tree
	}
	// must no way go here
	return nil
}

func (t *Tree) destroy() {
	for _, key := range t.tree.Keys() {
		t.tree.Delete(key)
	}
	t.tree = nil
}

func (t *Tree) Len() int {
	return t.tree.Len()
}

func (t *Tree) Insert(v *simOrderType) {
	t.tree.Set(oidPriceType{oid: int32(v.oid), price: int32(v.price)}, v)
}

func (t *Tree) First() *Iterator {
	it := Iterator{}
	it.it = t.tree.Iter()
	it.it.First()
	return &it
}

func (it *Iterator) First() *simOrderType {
	if !it.it.First() {
		return nil
	}
	return it.it.Value()
}

func (it *Iterator) Get() *simOrderType {
	if it.it.End() {
		return nil
	}
	return it.it.Value()
}

func (it *Iterator) Next() *simOrderType {
	if !it.it.Next() {
		return nil
	}
	return it.it.Value()
}
